Security News
Input Validation Vulnerabilities Dominate MITRE's 2024 CWE Top 25 List
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.
The 'websocket' npm package provides a WebSocket server and client for Node.js, allowing for real-time, bidirectional communication between a client and server over a single, long-lived connection.
WebSocket Server
This code sets up a basic WebSocket server using the 'websocket' package. It listens for incoming WebSocket connections, accepts them, and allows for message exchange between the server and connected clients.
const WebSocketServer = require('websocket').server;
const http = require('http');
const server = http.createServer((request, response) => {
response.writeHead(404);
response.end();
});
server.listen(8080, () => {
console.log('Server is listening on port 8080');
});
const wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', (request) => {
const connection = request.accept(null, request.origin);
console.log('Connection accepted.');
connection.on('message', (message) => {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF('Hello from server!');
}
});
connection.on('close', (reasonCode, description) => {
console.log('Peer ' + connection.remoteAddress + ' disconnected.');
});
});
WebSocket Client
This code demonstrates how to create a WebSocket client using the 'websocket' package. The client connects to a WebSocket server, handles connection events, and sends random numbers to the server at regular intervals.
const WebSocketClient = require('websocket').client;
const client = new WebSocketClient();
client.on('connectFailed', (error) => {
console.log('Connect Error: ' + error.toString());
});
client.on('connect', (connection) => {
console.log('WebSocket Client Connected');
connection.on('error', (error) => {
console.log('Connection Error: ' + error.toString());
});
connection.on('close', () => {
console.log('Connection Closed');
});
connection.on('message', (message) => {
if (message.type === 'utf8') {
console.log('Received: ' + message.utf8Data);
}
});
function sendNumber() {
if (connection.connected) {
const number = Math.round(Math.random() * 0xFFFFFF);
connection.sendUTF(number.toString());
setTimeout(sendNumber, 1000);
}
}
sendNumber();
});
client.connect('ws://localhost:8080/', 'echo-protocol');
The 'ws' package is a popular WebSocket implementation for Node.js. It is known for its performance and simplicity. Compared to 'websocket', 'ws' is more lightweight and has a larger community, making it a preferred choice for many developers.
The 'socket.io' package provides a WebSocket-like API but with additional features such as fallback to HTTP long-polling, automatic reconnection, and rooms/namespaces support. It is more feature-rich compared to 'websocket' and is suitable for applications requiring more advanced real-time communication capabilities.
This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and 13 for Node. There are some example client and server applications that implement various interoperability testing protocols in the "test/scripts" folder.
You can read the full API documentation in the docs folder.
Current Version: 1.0.35 - Release 2024-05-12
All current browsers are fully* supported.
(Not all W3C WebSocket features are supported by browsers. More info in the Full API documentation)
There are some basic benchmarking sections in the Autobahn test suite. I've put up a benchmark page that shows the results from the Autobahn tests run against AutobahnServer 0.4.10, WebSocket-Node 1.0.2, WebSocket-Node 1.0.4, and ws 0.3.4.
(These benchmarks are quite a bit outdated at this point, so take them with a grain of salt. Anyone up for running new benchmarks? I'll link to your report.)
The very complete Autobahn Test Suite is used by most WebSocket implementations to test spec compliance and interoperability.
In your project root:
$ npm install websocket
Then in your code:
var WebSocketServer = require('websocket').server;
var WebSocketClient = require('websocket').client;
var WebSocketFrame = require('websocket').frame;
var WebSocketRouter = require('websocket').router;
var W3CWebSocket = require('websocket').w3cwebsocket;
W3CWebSocket
class).Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary.
#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
This is a simple example client that will print out any utf-8 messages it receives on the console, and periodically sends a random number.
This code demonstrates a client in Node.js, not in the browser
#!/usr/bin/env node
var WebSocketClient = require('websocket').client;
var client = new WebSocketClient();
client.on('connectFailed', function(error) {
console.log('Connect Error: ' + error.toString());
});
client.on('connect', function(connection) {
console.log('WebSocket Client Connected');
connection.on('error', function(error) {
console.log("Connection Error: " + error.toString());
});
connection.on('close', function() {
console.log('echo-protocol Connection Closed');
});
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log("Received: '" + message.utf8Data + "'");
}
});
function sendNumber() {
if (connection.connected) {
var number = Math.round(Math.random() * 0xFFFFFF);
connection.sendUTF(number.toString());
setTimeout(sendNumber, 1000);
}
}
sendNumber();
});
client.connect('ws://localhost:8080/', 'echo-protocol');
Same example as above but using the W3C WebSocket API.
var W3CWebSocket = require('websocket').w3cwebsocket;
var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol');
client.onerror = function() {
console.log('Connection Error');
};
client.onopen = function() {
console.log('WebSocket Client Connected');
function sendNumber() {
if (client.readyState === client.OPEN) {
var number = Math.round(Math.random() * 0xFFFFFF);
client.send(number.toString());
setTimeout(sendNumber, 1000);
}
}
sendNumber();
};
client.onclose = function() {
console.log('echo-protocol Client Closed');
};
client.onmessage = function(e) {
if (typeof e.data === 'string') {
console.log("Received: '" + e.data + "'");
}
};
For an example of using the request router, see libwebsockets-test-server.js
in the test
folder.
A presentation on the state of the WebSockets protocol that I gave on July 23, 2011 at the LA Hacker News meetup. WebSockets: The Real-Time Web, Delivered
FAQs
Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.
The npm package websocket receives a total of 596,981 weekly downloads. As such, websocket popularity was classified as popular.
We found that websocket demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.